package com.zmn.oms.zmn.business.impl.comment;

import com.google.common.collect.Lists;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.comment.ZsCommentRemarkDTO;
import com.zmn.oms.model.dto.remark.OrderRemarkDTO;
import com.zmn.oms.model.dto.remark.OrderRemarkDetailDTO;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.zmn.business.interfaces.comment.ZsOrderCommentBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ZsOrderCommentBServiceImpl implements ZsOrderCommentBService {

    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    OrderRemarkBService orderRemarkBService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_COMMENT_REMARK)
    public void saveRemark(ZsCommentRemarkDTO commentRemarkDTO) throws OmsBaseException {
        OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(commentRemarkDTO.getOrderId(), commentRemarkDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_COMMENT_REMARK);
        if (!operatePermission.getCanOperate()) {
            throw new OmsBaseException(operatePermission.getMsg());
        }

        // 保存评价备注
        OrderRemarkDTO orderRemarkDTO = new OrderRemarkDTO();
        orderRemarkDTO.setOrderId(commentRemarkDTO.getOrderId());
        orderRemarkDTO.setWorkId(commentRemarkDTO.getWorkId());
        orderRemarkDTO.setContent(commentRemarkDTO.getRemarkContent());
        orderRemarkDTO.setOperator(commentRemarkDTO.getOperator());
        orderRemarkDTO.setOperatorId(commentRemarkDTO.getOperatorId());

        List<OrderRemarkDetailDTO> detailDTOList = Lists.newArrayList();
        List<KVDict> replyVisitCodeMapList = commentRemarkDTO.getCodeMapList();
        replyVisitCodeMapList.forEach(codeMap -> {
            OrderRemarkDetailDTO detailDTO = new OrderRemarkDetailDTO();
            detailDTO.setMapId(Integer.parseInt((String) codeMap.getValue()));
            detailDTO.setMapName(codeMap.getText());
            detailDTOList.add(detailDTO);
        });
        orderRemarkDTO.setDetailDTOList(detailDTOList);

        // 保存评价备注数据
        orderRemarkBService.insertOrderRemark(orderRemarkDTO, OrderConsts.ORDER_REMARK_TYPE_COMMENT_REMARK);
    }
}
